package utils

import (
	"github.com/antlabs/quickws"
	"ubt-aio-service/app/pkg/logger"
)

type WsHandler struct{}

// OnOpen 当连接成功后触发
func (e *WsHandler) OnOpen(c *quickws.Conn) {
	if err := c.WriteMessage(quickws.Text, []byte("Welcome to the world of WebSocket~!")); err != nil {
		logger.Error("发送消息失败。" + err.Error())
	}
}

// OnMessage 当收到消息后触发
func (e *WsHandler) OnMessage(c *quickws.Conn, op quickws.Opcode, msg []byte) {
	if string(msg) == "ping" {
		if err := c.WriteMessage(quickws.Text, []byte("pong")); err != nil {
			logger.Error("发送消息失败。" + err.Error())
			return
		}
	}
}

// OnClose 当连接关闭后触发
func (e *WsHandler) OnClose(_ *quickws.Conn, err error) {
	if err != nil {
		logger.Error("WebSocket连接关闭。" + err.Error())
	}
}
